package com.healthcarex.hip.saas.mybatis.service.impl;

import com.healthcarex.hip.saas.common.model.BaseModel;
import com.healthcarex.hip.saas.mybatis.config.MyMapper;
import com.healthcarex.hip.saas.mybatis.dao.CommonDao;
import com.healthcarex.hip.saas.mybatis.service.IBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author chenpan
 * @ClassName: BaseServiceImpl
 * description:
 * @date 2018-04-02 15:44
 */
public abstract class BaseServiceImpl<T extends BaseModel> implements IBaseService<T> {

    @Autowired
    protected MyMapper<T> mapper;

    @Autowired
    protected CommonDao commonDao;

    @Override
    public Integer getSequence(String seqName) {
        return commonDao.getSequence(seqName);
    }

    @Override
    public List selectAll() {
        return mapper.selectAll();
    }

    @Override
    public T selectById(Object id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
    public int save(T entity) {
        return mapper.insertSelective(entity);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
    public int delete(Object id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateAll(T entity) {
        return mapper.updateByPrimaryKey(entity);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateNotNull(T entity) {
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public List selectByExample(Object example) {
        return mapper.selectByExample(example);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int batchDelete(List list, String property, Class clazz) {
        Example example = new Example(clazz);
        example.createCriteria().andIn(property, list);
        return this.mapper.deleteByExample(example);
    }
}
